# -*- coding: utf-8 -*-

# Copyright (C) 2011 Dimitri Linten

#This file is part of pyQuiz.
#
#pyQuiz is free software: you can redistribute it and/or modify
#it under the terms of the GNU Lesser General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#ThunderStorm is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public License
#along with pyQuiz.  If not, see <http://www.gnu.org/licenses/>.

# TODO: IPLOAD to google codes


from setupQuiz import *
from resultView import *

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.interactive(True)
import xlwt, xlrd
import os
import csv

def GenerateRandomQuiz(Q,Naam):
    
    import random

    nb_ploegen=20
    
    def get_random_word(wordLen):
        word = ''
        for i in range(wordLen):
            word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789')
        return word
    
    def random_ints(num, lower=0, upper=1):
                return [random.randrange(lower,upper+1) for i in range(num)]
            
    # Randow string arrays (30)   
    Ploegen=[]
    for i in np.arange(nb_ploegen):
        Ploegen.append(get_random_word(10))
    
    Q.new(Ploegen,Naam)
    
    # Fill with random scores
    for elem in enumerate(Ploegen):

        for question in np.arange(10):
            Q.addScores(elem[0]+1,int(question+1),random_ints(10))
            
        for question in ['a','b','c','d','e']:
            Q.addScores(elem[0]+1,question,random.randrange(11))
            

class Room(object):
    '''
    classdocs
    '''

    def __init__(self):
        
        self.sessionNames={1: 'Verkeer',
               2: 'Actualiteit',
               3: 'Film, TV, de boekjes',
               4: 'Natuur & Wetenschap',
               5: 'Sport',
               6: 'Geschiedenis',
               7: 'Eten en drinken',
               8: 'Aarderijkskunde',
               9: 'Toets',
               10: 'Muziek'}

        self.TableList=[]
        self.ploegen=[]
        self.xls=[]
        
    def setup(self,naam):
        " Read in Ploeg names, and create an xls file"
 
        
        reader = csv.reader(open("inputPloegen.csv", "rb"))
        for row in reader:
            self.ploegen.append(row[1])
            
        self.new(self.ploegen,naam)
        
        
    def new(self,headings,Naam):
        " old method use New"
        self.Naam=Naam
        self.ploegen=headings
        
        self.PloegenScores={} 
        # Start scores
        for elem in headings:
            self.PloegenScores[elem]=0
            
#        print self.PloegenId
        
        book = xlwt.Workbook()
        for elem in headings:
            sheet = book.add_sheet(elem,cell_overwrite_ok=True)
            self.TableList.append(sheet)
        self.xls=book
        
        
        # Fill with zeros as default data
        for elem in enumerate(self.ploegen):
            self.addScores(elem[0]+1,'schift',0)
            for question in np.arange(10):
                self.addScores(elem[0]+1,int(question+1),np.zeros(10))
                
            for question in ['a','b','c','d','e']:
                self.addScores(elem[0]+1,question,0)
            
        
        self.saveFile()
        return book
    
    def addScores(self,tablenr,sessionnr,data):
        
        # Check on data
        if type(sessionnr) is str:
            if sessionnr == 'schift':
                sheet=self.TableList[tablenr-1]
                sheet.write(0,14,data)
                self.saveFile()
            else:
                tablenr=tablenr-1 # start at 0
                midlist=['a','b','c','d','e']
                sheet=self.TableList[tablenr]
                sheet.write(midlist.index(sessionnr),12,data)
                self.saveFile()
        else:
            if np.array(data).sum()<11 and len(data)==10 and ( set(data) == set([0,1])  or set(data)==( set([1]) ) or set(data)==( set([0]) )):
                tablenr=tablenr-1 # start at 0
                sessionnr=sessionnr-1
                sheet=self.TableList[tablenr]
                for elem in range(len(data)):
                    sheet.write(sessionnr,elem,data[elem])
                # Write total score of each session
                sheet.write(sessionnr,len(data),np.array(data).sum())
                self.saveFile()
            else:
                print "Wrong Entry ! Sheet " + str(tablenr) + " Row " +str(sessionnr)


    def saveFile(self):
        self.xls.save(self.Naam+'.xls') 
        
    def load(self, file_name):
        """ Load an excisting xls fle"""
        self.Naam = file_name
        booko = xlrd.open_workbook(file_name +'.xls')
        # read in the data 
        ploegen=[]
        data=[]
        for elem in booko.sheet_names():
            ploegen.append(str(elem))
            raw_sheet = booko.sheet_by_name(elem)
            rowdata=[]
            for row in range(raw_sheet.nrows):
                (types, values) = (raw_sheet.row_types(row), raw_sheet.row_values(row))
                rowdata.append(values)
            data.append(rowdata)
        
#        print ploegen
#        print data
        del booko
        cmd="del " + self.Naam +".xls"
        os.system(cmd)
        
        
#        write out the new book
        self.TableList=[]
        self.ploegen=[]
        self.xls=[]
        self.new(ploegen,self.Naam)
        # loop over tabs and load the table ( also scores)
        
        for tablenr in np.arange(len(self.TableList)):
                sheet=self.TableList[tablenr]
                dataSheet=data[tablenr]
                for i in range(len(dataSheet)):
                    for j in range(len(dataSheet[i])):
                        sheet.write(i,j,dataSheet[i][j])
#                # Write total score of each session
        self.saveFile()
        
    def read(self):
        """ read in the input file that serves as input during the quiz
        """
        data =np.loadtxt('input.csv', delimiter = ',', skiprows = 1)
        for rows in data:
#            print rows
            self.addScores(int(rows[0]),int(rows[1]),rows[2:])
        
        reader = csv.reader(open("inputTussen.csv", "rb"))
        for row in reader:
            print row
            self.addScores(int(row[0]),row[1],int(row[2]))

        dataSchift = np.loadtxt('inputSchifting.csv', delimiter = ',', skiprows = 1)
        
        for rows in dataSchift:
            self.addScores(int(rows[0]),'schift',int(rows[1]))

    def CalculateCurrentScores(self):
        
        booko = xlrd.open_workbook(self.Naam +'.xls')
        
        for elem in booko.sheet_names():

            raw_sheet = booko.sheet_by_name(elem)         
            self.PloegenScores[elem]=np.array(raw_sheet.col_values(10)).sum()
            
            try:
                temp=raw_sheet.col_values(12)
                temp2=list(temp)
                for el in temp:
                    if el=='':
                        temp2.remove(el)
    #                    print temp2
                som_tussen_rondes=np.array(temp2).sum()
                
                self.PloegenScores[elem]=self.PloegenScores[elem]+som_tussen_rondes
            except:
                pass
            
        return self.PloegenScores 

    def CalculateCurrentScoresTopic(self,n):
        
        booko = xlrd.open_workbook(self.Naam +'.xls')
        
        for elem in booko.sheet_names():

            raw_sheet = booko.sheet_by_name(elem)       
            if n==13:
                        temp=raw_sheet.col_values(12)
                        temp2=list(temp)
                        for el in temp:
                            if el=='':
                                temp2.remove(el)
                        self.PloegenScores[elem]=np.array(temp2).sum()
            else:            
            # Am overwriting the self.PloegenScores
                self.PloegenScores[elem]=np.array(raw_sheet.col_values(n-1)).sum()
        return self.PloegenScores

    def CalculateSchifting(self):
        "calculates for each ploeg how far they are away from target"
        self.n=204.25
        booko = xlrd.open_workbook(self.Naam +'.xls')
        for elem in booko.sheet_names():
            raw_sheet = booko.sheet_by_name(elem)
            temp=raw_sheet.col_values(14)
            temp2=list(temp)
            for el in temp:
                if el=='':
                    temp2.remove(el)
            self.PloegenScores[elem]=np.abs(self.n-np.array(temp2).sum())
            
        #print self.PloegenScores
        return self.PloegenScores

    def PrintResultQuiz(self):
        "To be Tested"
        book = xlwt.Workbook()
        
        #Writes the total results in a new excel sheet
        sheet=book.add_sheet('Final',cell_overwrite_ok=True)
        
        data=self.CalculateCurrentScores()
        
        i=len(data.items())-1
        
        for w in sorted(data.items(), key=lambda x: x[1]):
            
            sheet.write(i,0,w[0])
            sheet.write(i,1,w[1])
            i=i-1
      
                # Print results schiftings ronde
        sheet=book.add_sheet('Schifting',cell_overwrite_ok=True)
        
        data=self.CalculateSchifting()
        
        i=0
            
        for w in sorted(data.items(), key=lambda x: x[1]):
            
            sheet.write(i,0,w[0])
            sheet.write(i,1,w[1])
            i=i+1
            
        
        
        
        #For category abcde
        #Writes the total results in a new excel sheet
        
        try:
            
            sheet=book.add_sheet('Tussenrondes',cell_overwrite_ok=True)
            
            data=self.CalculateCurrentScoresTopic(13)
            
            i=len(data.items())-1
            
            for w in sorted(data.items(), key=lambda x: x[1]):
                
                sheet.write(i,0,w[0])
                sheet.write(i,1,w[1])
                i=i-1
        except:
            pass
        
        
        # For category of Questions write the scores 
        
        for j in np.arange(10)+1:
                    #Writes the total results in a new excel sheet
            sheet=book.add_sheet(self.sessionNames[j],cell_overwrite_ok=True)
            
            data=self.CalculateCurrentScoresTopic(j)
            
            i=len(data.items())-1
            
            for w in sorted(data.items(), key=lambda x: x[1]):
                
                sheet.write(i,0,w[0])
                sheet.write(i,1,w[1])
                i=i-1

        book.save(self.Naam +'Results' + '.xls')
                

            
if __name__=="__main__":
    
    Naam='DeWegwijzerQuiz'
    Q=Room()
    Q.setup(Naam)
    Q.read()
    Q.PrintResultQuiz()


##    
#    Naam='DeWegwijzerQuiz'
#    Q=Room()
#    Q.load('DeWegwijzerQuiz')
#    Q.PrintResultQuiz()
#
##    

#    
#    Q=Room()
#    
#    
#    # Input by user
#    GenerateRandomQuiz(Q,Naam)
    
#    Q.CalculateCurrentScores()
    
#    del Q
#    
#    Q=Room()
#    Q.load('DeWegwijzerQuiz')
    
#    Ploegen=['pipi','kaka','boeboe']
    
#    Q.new(Ploegen,Naam)
#    
#    Q.addScores(1,1,[1,0,1,0,1,1,0,1,1,0])
#    
#    Q.addScores(1,'a',5)
#    
#    Q.addScores(1,2,[1,0,1,1,1,1,0,1,1,0])
#    Q.addScores(1,'b',6)
#    Q.addScores(1,3,[1,0,1,0,1,1,1,1,1,0])
#    Q.addScores(1,'c',8)
#    
#    
#    Q.addScores(1,4,[1,0,0,0,1,1,0,1,1,0])
#    Q.addScores(1,5,[1,0,1,1,1,1,0,1,1,0])
#    Q.addScores(1,6,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(1,7,[1,1,1,0,1,1,1,1,1,1])
#    Q.addScores(1,8,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(1,9,[1,0,1,1,1,1,0,1,1,1])
#    Q.addScores(1,10,[1,0,1,0,1,0,0,1,1,0])
#    
#    Q.addScores(2,1,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,2,[1,0,1,0,1,1,0,1,0,1])
#    Q.addScores(2,3,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,4,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,5,[1,0,1,0,1,1,1,1,1,1])
#    Q.addScores(2,6,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,7,[1,0,1,0,1,1,0,1,1,1])
#    Q.addScores(2,8,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,9,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(2,10,[1,0,1,0,1,1,0,1,1,0])
#    
#    Q.addScores(3,1,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,2,[0,0,1,0,1,1,0,1,0,1])
#    Q.addScores(3,3,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,4,[1,1,1,0,1,1,0,1,1,0])
#    Q.addScores(3,5,[1,0,1,0,1,1,1,1,1,1])
#    Q.addScores(3,6,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,7,[1,1,1,1,1,1,1,1,1,1])
#    Q.addScores(3,8,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,9,[0,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,10,[1,0,1,0,1,1,0,1,1,0])
#    Q.addScores(3,10,[1,1,1,0,1,1,0,1,1,0])
#    
#    
##    V=View(Q)
#    V.CurrentScores()